package com.lovegu.collection.list;

import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author 老顾
 * @title: ListTest
 * @projectName java-restudy
 * @email: 1437594522@qq.com
 * @date 2022/9/24 10:42
 */
public class ListTest {
    public List<String> names;
    @Before
    public void add() {
        names = new ArrayList<>();
        names.add("tom");
        names.add("lucy");
        names.add("lucy");
        names.add("lucy");
        names.add("jerry");
    }
    @Test
    public void testFor(){
        for (int i = 0; i < names.size(); i++) {
            System.out.println(names.get(i));
        }
    }
    @Test
    public void testIterator(){
        Iterator<String> iterator = names.iterator();
        // 每次都判断一下是不是有下一个，有的话，继续遍历
        while (iterator.hasNext()){
            // 获取下一个
            String name = iterator.next();
            System.out.println(name);
        }
    }
    @Test
    public void testEnhancedFor(){
        for (String name : names){
            System.out.println(name);
        }
    }
    @Test
    public void testDelByFor(){
        for (int i = 0; i < names.size(); i++) {
            if("lucy".equals(names.get(i))){
                names.remove(i);
            }
        }
        System.out.println(names);
    }
    @Test
    public void testDelByFor2(){
        for (int i = 0; i < names.size(); i++) {
            if("lucy".equals(names.get(i))){
                names.remove(i);
                // 回调指针：
                i--;
            }
        }
        System.out.println(names);
    }
    @Test
    public void testDelByIterator(){
        Iterator<String> iterator = names.iterator();
        while (iterator.hasNext()){
            // 记住next(),只能调用一次，因为每次调用都会选择下一个
            String name = iterator.next();
            if("lucy".equals(name)){
                iterator.remove();
            }
        }
        System.out.println(names);
    }
    @Test
    public void testDelByFor3(){
        for (int i = names.size()-1; i > 0; i--) {
            if("lucy".equals(names.get(i))){
                names.remove(i);
            }
        }
        System.out.println(names);
    }
}
